import { Request, Response } from 'express';
import { UserInfoModel } from '../models/userInfoModel';
import { UserModel } from '../models/user'
export class UserInfoController {
  private userInfoModel: UserInfoModel;
  private UserModel: UserModel
  constructor() {
    this.userInfoModel = new UserInfoModel();
    this.UserModel = new UserModel()
  }
  save = async (req: Request, res: Response): Promise<void> => {
     try {
      const user = req.user!;
      const { headImg, workUrl, motto, birthDay, sex, hobby, ortherInfo } = req.body;
      const hobbyStr = hobby.join(',')
      const userInfo = {
          userId: user.userId as string,
          headImg,
          workUrl,
          motto,
          birthDay,
          sex,
          hobby: hobbyStr,
          ortherInfo: ortherInfo || ''
        }
      const userStoreInfo = await this.userInfoModel.findByUserId(user.userId as string);
      let resStroe: any;
      if (userStoreInfo) {
        resStroe = await this.userInfoModel.updateUserInfo(userInfo);
      } else {
        resStroe = await this.userInfoModel.create(userInfo);
      }
      if (resStroe) {
        res.json({ code: 200, message: '保存成功' });
      } else {
        res.status(200).json({ code: 400, message: '保存失败' });
      }
    } catch (error) {
      console.error('保存用户信息错误:', error);
      res.status(500).json({ message: '服务器内部错误' });
    }
  }
  getInfo = async (req: Request, res: Response): Promise<void> => {
    try {
      const user = req.user!;
      const userInfo = await this.userInfoModel.findByUserId(user.userId as string);
      if (!userInfo) {
        res.json({
          code: 200,
          data: userInfo,
          message: '数据获取成功！'
        })
        return
      }
      res.json({
        code: 200,
        data: {
          ...userInfo,
          hobby: userInfo.hobby.split(',')
        },
        message: '数据获取成功！'
      });
    } catch (error) {
      console.error('获取用户信息错误:', error);
      res.status(500).json({ message: '服务器内部错误' });
    }
  }
  getPageData = async (req: Request, res: Response): Promise<void> => {
    try {
      const { page, pageSize } = req.query;
      const pageInfo = await this.userInfoModel.getPageInfo(Number(page), Number(pageSize));
      const userNames = await this.UserModel.getUsersByUserIds(pageInfo.rows.map(item => item.userId))
      const relUserNames = new Map();
      userNames.forEach(item => {
        relUserNames.set(item.userId, item)
      })
      const rows = pageInfo.rows.map((item) => {
        return {
          ...item,
          userName: relUserNames.get(item.userId)?.username,
          ip: relUserNames.get(item.userId)?.register_ip
        }
      })
      const data = {
        rows,
        total: pageInfo.total
      }
      res.json({ data, message: '获取用户列表成功', code: 200 });
    } catch (error) {
      console.error('获取用户信息错误:', error);
      res.status(500).json({ message: '服务器内部错误' });
    }
  }

}